<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/1/31
 * Time: 14:07
 */

namespace app\api\controller\v1;

use app\common\Server\Redis;


class Auth extends Base
{
    const PREFIX = 'CACHE:TOKEN:%s';

    public function __construct($array)
    {
        parent::__construct($array);
        $rtn = $this->checkToken();
        //TODO 后续整合
        //token错误
        if($rtn === 1){
            echo json_encode([
                'code' => 801005,
                'msg' => 'token验证失败',
                'data' => []
            ]);die;
            //参数不全
        }elseif ($rtn === 2){
            echo json_encode([
                'code' => 999993,
                'msg' => '必传参数数据不可为空',
                'data' => []
            ]);die;
        }
    }

    /**
     * 验证token
     * @return int
     */
    final public function checkToken()
    {
        $app_name = ($this->arr['app_name'] ?? '') === 'shr' ? 'shr' : '';//如果app_name不为空且不是‘shr’置为空
        if(($token = $this->arr['token'] ?? '') && ($uid = $this->arr['uid'] ?? 0)){
            $redis = new Redis();
            $hredis = $redis->handler();
            $ckey  = $app_name . sprintf(self::PREFIX, $uid);
            $rtoken = $hredis->get($ckey);
            if($token != $rtoken){
                return 1;
            }
            return true;
        }else{
            return 2;
        }
    }
}